/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * NewCityDialog.java
 *
 * Created on 8.12.2011, 13:33:04
 */
package view;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import logic.business.DataEditor;
import logic.business.exceptions.MalformedDataException;

/**
 *
 * @author zhenia
 */
public class NewCityDialog extends javax.swing.JDialog {

    private boolean result;
    private final DataEditor dataEditor;

    /** Creates new form NewCityDialog */
    NewCityDialog(DataEditor de) {
        initComponents();
        dataEditor = de;

    }

    public boolean execute() { // метод для "общения" с родительским окном
        this.setVisible(true); // прорисовать дочернее окно; в данном месте выполнение программы приостановится, ожидая окончания работы пользователя (в нашем случае - функции dispose())
        return this.result; // вернуть в качестве результата условное значение нажатой кнопки
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        nameLabel = new javax.swing.JLabel();
        populationLabel = new javax.swing.JLabel();
        name = new javax.swing.JTextField();
        population = new javax.swing.JTextField();
        cancel = new javax.swing.JButton();
        ok = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("New Place");

        nameLabel.setText("Name");
        nameLabel.setName("nameLabel"); // NOI18N

        populationLabel.setText("Population");
        populationLabel.setName("populationLabel"); // NOI18N

        name.setName("name"); // NOI18N
        name.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nameActionPerformed(evt);
            }
        });

        population.setName("population"); // NOI18N

        cancel.setText("Cancel");
        cancel.setName("cancel"); // NOI18N
        cancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelActionPerformed(evt);
            }
        });

        ok.setText("OK");
        ok.setName("ok"); // NOI18N
        ok.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(260, Short.MAX_VALUE)
                .addComponent(ok)
                .addGap(18, 18, 18)
                .addComponent(cancel)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(populationLabel)
                        .addGap(42, 42, 42)
                        .addComponent(population))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(nameLabel)
                        .addGap(65, 65, 65)
                        .addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(224, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(nameLabel)
                    .addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(population, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(populationLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 204, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(ok)
                    .addComponent(cancel))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void nameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nameActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_nameActionPerformed

    private void cancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelActionPerformed

        this.result = false;
        this.dispose();
        // TODO add your handling code here:
}//GEN-LAST:event_cancelActionPerformed

    private void okActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okActionPerformed
        try {

            if (name.getText().isEmpty() || population.getText().isEmpty()) {
                JOptionPane.showMessageDialog(this,
                        "City name and population can't be null",
                        "Warning",
                        JOptionPane.WARNING_MESSAGE);
            } else if (Integer.parseInt(population.getText()) < 0) {
                JOptionPane.showMessageDialog(this,
                        "Population must be positive integer",
                        "Warning",
                        JOptionPane.WARNING_MESSAGE);

            } else {
                dataEditor.addNewPlace(name.getText().toLowerCase(), name.getText(), "0", population.getText());

                this.result = true;
                this.dispose();
            }
        } catch (MalformedDataException ex) {
            Logger.getLogger(NewCityDialog.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(this,
                    "Population must be positive integer",
                    "Warning",
                    JOptionPane.WARNING_MESSAGE);
        }
        //        }
}//GEN-LAST:event_okActionPerformed
    public DataEditor getDataEditor() { // метод для "общения" с родительским окном
        //  this.setVisible(true); // прорисовать дочернее окно; в данном месте выполнение программы приостановится, ожидая окончания работы пользователя (в нашем случае - функции dispose())
        return this.dataEditor; // вернуть в качестве результата условное значение нажатой кнопки
    }
    /**
     * @param args the command line arguments
     */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancel;
    private javax.swing.JTextField name;
    private javax.swing.JLabel nameLabel;
    private javax.swing.JButton ok;
    private javax.swing.JTextField population;
    private javax.swing.JLabel populationLabel;
    // End of variables declaration//GEN-END:variables
}
